<?php
/**
 * 对异常类进行扩展
 */

namespace support\exception;


use support\facade\Logger;
use Webman\Http\Response;
use Webman\Http\Request;

class ErrorHandler extends \Webman\Exception\ExceptionHandler
{
    public function render(Request $request, \Throwable $exception): Response
    {

        $code = $exception->getCode();
        $message = $exception->getMessage();
        $debug = $this->_debug ?? $this->debug;

        if($exception instanceof DumpException){
            $hears = ['Content-Type' => 'text/html;charset=utf-8'];
            return new \support\Response('200',$hears,'<pre>'.$exception->getMessage().'</pre>');
        }
        $json = [
            'code'=>$code,
            'msg'=>$message,
        ];
        // 处理自定义的异常
        if($exception instanceof ValidationException){
            $json = ['code' => $code ?: 500, 'msg' => $message ?: '参数验证失败'];
        }
        if($exception instanceof ApiException){
            $json = ['code' => $code ?: 500, 'msg' => $message ?: '接口请求失败'];
        }

        // 记录未知错误
        if($exception instanceof \Throwable){
            Logger::err("[{$code}]异常错误：{$message} 错误位置：{$exception->getFile()} line：{$exception->getLine()}");
        }

        if ($request->expectsJson()) {
            $debug && $json['traces'] = $exception->getTraceAsString();
            return new Response(200, ['Content-Type' => 'application/json'],
                \json_encode($json, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
        }


        if($debug){
            $error =\nl2br((string)$exception);
            return new Response(500, [], $error);
        }else{
            // 抛出错误页面
            return view('/../../public/500', ['exception' => $exception->getMessage()], '')->withStatus(500);
        }
    }
}